import React, { useState } from 'react';
import JSZip from './jszip.min.js';
import X2JS from './xml2json.min.js';

/**
 * 定义一个React函数式组件Var2JavaEntity，它接收一个Urule变量库的XML格式字符串，并将其转换为Java实体类，以及提供下载功能
 */
const Var2JavaEntity = () => {
    const [uruleVar, setUruleVar] = useState('');
    const [javaEntityMap, setJavaEntityMap] = useState(new Map());
    const [javaEntity, setJavaEntity] = useState('');

    const uruleVarToJavaEntity = () => {
        if (!uruleVar) {
            alert("请输入Urule变量库文件源码！");
            return;
        }

        setJavaEntity('');

        try {
            const data = loadXMLDoc(uruleVar);
            const categoryList = data["variable-library"]["category"];
            let entityContent = '';

            categoryList.forEach(category => {
                const clazz = category["_clazz"];
                const _package = clazz.substring(0, clazz.lastIndexOf('.'));
                let entity = `package ${_package};\n\n`;
                entity += "import com.bstek.urule.model.Label;\n";
                entity += dealVarType(category) + "\n";
                const entityName = clazz.split('.').pop();
                entity += `public class ${entityName} {\n\n`;

                const varList = category["var"];
                varList.forEach(v => {
                    const varLabel = v["_label"];
                    const varType = v["_type"];
                    const varName = v["_name"];
                    if (varName.indexOf(".") === -1) {
                        entity += `    @Label("${varLabel}")\n`;
                        entity += `    private ${varType} ${varName};\n`;
                    }
                });

                entity += "\n";

                varList.forEach(v => {
                    const varLabel = v["_label"];
                    const varType = v["_type"];
                    const varName = v["_name"];
                    if (varName.indexOf(".") === -1) {
                        entity += `    public ${varType} get${varName[0].toUpperCase()}${varName.substr(1)}() { return ${varName}; }\n\n`;
                        entity += `    public void set${varName[0].toUpperCase()}${varName.substr(1)}(${varType} ${varName}) { this.${varName} = ${varName}; }\n\n`;
                    }
                });

                entity += "}\n";
                entityContent += entity + "\n=============================================================================================================================================\n";
                setJavaEntityMap(prevState => new Map([...prevState, [entityName, entity]]));
            });

            setJavaEntity(entityContent);
        } catch (error) {
            alert("Urule变量库文件源码格式有误！");
            console.error(error);
        }
    };

    const dealVarType = (category) => {
        const varTypeSet = new Set();
        let importStr = '';
        const varList = category["var"];

        varList.forEach(v => {
            const varType = v["_type"];
            const varName = v["_name"];
            if (varName.indexOf(".") === -1) {
                if (varType === "Char") {
                    v["_type"] = "char";
                }
                varTypeSet.add(varType);
            }
        });

        varTypeSet.forEach(varType => {
            if (varType === "List") {
                importStr += "import java.util.List;\n";
            } else if (varType === "Set") {
                importStr += "import java.util.Set;\n";
            } else if (varType === "Map") {
                importStr += "import java.util.Map;\n";
            } else if (varType === "Date") {
                importStr += "import java.util.Date;\n";
            } else if (varType === "BigDecimal") {
                importStr += "import java.math.BigDecimal;\n";
            }
        });

        return importStr;
    };

    const loadXMLDoc = (data) => {
        const x2js = new X2JS();
        const json = x2js.xml_str2json(data);
        return json;
    };

    const downloadJavaEntity = () => {
        if (javaEntityMap.size === 0) {
            alert("未发现转化完成的java实体类");
        } else if (window.confirm("确定下载转换完成的java实体类吗？")) {
            const zip = new JSZip();
            javaEntityMap.forEach((val, key) => {
                zip.file(`${key}.java`, val);
            });
            zip.generateAsync({ type: "blob" }).then(content => {
                const link = document.createElement('a');
                link.download = "javaEntity.zip";
                link.href = URL.createObjectURL(content);
                link.click();
                URL.revokeObjectURL(link.href);
            });
        }
    };

    return (
        <div>
            <div>Urule变量库文件源码：</div>
            <textarea
                id="UruleVar"
                rows="10"
                cols="30"
                style={{ width: '1450px', height: '175px' }}
                value={uruleVar}
                onChange={e => setUruleVar(e.target.value)}
            />
            <div>
                <input
                    id="convertBt"
                    type="button"
                    value="转换"
                    onClick={uruleVarToJavaEntity}
                />
                <input
                    id="download"
                    type="button"
                    value="下载Java实体类"
                    onClick={downloadJavaEntity}
                />
            </div>
            <div>Java实体类预览：</div>
            <textarea
                id="JavaEntity"
                rows="10"
                cols="30"
                style={{ width: '1450px', height: '350px' }}
                readOnly
                value={javaEntity}
            />
        </div>
    );
};

// 导出组件以便在其他地方使用
export default Var2JavaEntity;